package com.repository;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.model.User;
import com.repository.config.DataSourceUtil;


public class UserRepositoryImpl implements UserRepository{
	Connection conn;// 声明连接对象
	QueryRunner run;// 声明dbutils对象

	public UserRepositoryImpl() throws SQLException {
		this.conn = DataSourceUtil.getDataSource().getConnection();
		this.run = new QueryRunner();
	}
	
	//查询单个用户信息
	public User getOneUser(User user) {
		String sql = "select * from user where username = ?";
		try {
			return run.query(conn, sql, new BeanHandler<>(User.class), user.getUsername());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	// 用户注册
	public int addUser(User user) {
		String sql = "insert into user (username,password)values(?,?)";
		try {
			return run.update(conn, sql, user.getUsername(), user.getPassword());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return -1;
	}

	public List<User> getAllUser() {
		String sql = "select * from user";
		try {
			return run.query(conn, sql, new BeanListHandler<>(User.class));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
